package com.gexiaobao.pigeon.ui.breeding_pigeon

import android.os.Bundle
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.model.bean.BreedCategoryBean
import com.gexiaobao.pigeon.app.model.bean.BreedStatusList
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityBreedingPigeonManageBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterBloodPigeon
import com.gexiaobao.pigeon.ui.adapter.MyPopBloodLineAdapter
import com.gexiaobao.pigeon.viewmodel.BreedingPigeonViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2024/8/19 10:35
 * @Describe    : 种鸽管理
 */
class ActivityBreedingPigeonManage : BaseActivity<BreedingPigeonViewModel, ActivityBreedingPigeonManageBinding>() {

    private lateinit var loadSir: LoadService<Any>
    private val mAdapter: AdapterBloodPigeon by lazy { AdapterBloodPigeon(arrayListOf()) }
    private var mStatus = ""
    private var mCategory = ""
    private var mSex = ""
    private var mYear = ""

    private var adapterCategory: MyPopBloodLineAdapter? = null
    private val pWCategory: ListPopupWindow by lazy { ListPopupWindow(this) }
    private val mCategoryList: ArrayList<String> = arrayListOf()

    private var adapterStatus: MyPopBloodLineAdapter? = null
    private val pWStatus: ListPopupWindow by lazy { ListPopupWindow(this) }
    private val mStatusList: ArrayList<String> = arrayListOf()

    private var adapterSex: MyPopBloodLineAdapter? = null
    private val pWSex: ListPopupWindow by lazy { ListPopupWindow(this) }
    private val mSexList: ArrayList<String> = arrayListOf()

    private var adapterYear: MyPopBloodLineAdapter? = null
    private val pWYear: ListPopupWindow by lazy { ListPopupWindow(this) }
    private val mYearList: ArrayList<String> = arrayListOf()

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeSearch.editQuery.hint = getString(R.string.input_ring_and_name)

        mDatabind.includeSearch.editQuery.addTextChangedListener {
            mDatabind.includeSearch.ivClose.isVisible = it.toString().isNotEmpty()
        }

        mDatabind.includeSearch.editQuery.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    onRefresh(isRefresh = true)
                    hideSoftKeyboard(this)
                }

                else -> {}
            }
            false
        }

        loadSir = loadServiceInit(mDatabind.includeList.swipeRefreshLayout) {
            onRefresh(isRefresh = true)
        }

        onRefresh(isRefresh = true)

        mDatabind.includeList.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(this, 8f)))
            it.initFooter {
                onRefresh(isRefresh = false)
            }
        }

        mDatabind.includeList.swipeRefreshLayout.init {
            onRefresh(isRefresh = true)
        }

        setSexListPopup()

        eventViewModel.toRefreshData.observeInActivity(this) {
            if (it) {
                onRefresh(isRefresh = true)
            }
        }
        initListeners()
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取年份列表 */
        mViewModel.getYearResult.observe(this) {
            refreshArrowStatus(4)
            setYearListPopup(it.list)
        }
        /** 获获取种鸽类别 */
        mViewModel.getPgBreedCategoryResult.observe(this) {
            refreshArrowStatus(2)
            setCategoryListPopup(it.list)
        }
        /** 获取种鸽列表 */
        mViewModel.getPigeonResult.observe(this) {
            loadListData(it, mAdapter, loadSir, mDatabind.includeList.swipeRecyclerView, mDatabind.includeList.swipeRefreshLayout)
        }
        /** 获取种鸽状态  */
        mViewModel.getPgBreedStatusResult.observe(this) {
            refreshArrowStatus(1)
            setStatusListPopup(it.list)
        }
    }

    private fun initListeners() {
        pWStatus.setOnDismissListener {
            mDatabind.tvStatus.setTextColor(ContextCompat.getColor(this, R.color.comm_text_gray_dark))
            mDatabind.ivStatus.setBackgroundResource(R.mipmap.icon_arrow_down_solid)
            mDatabind.ivStatus.animate().rotationBy(-180F).setDuration(300).start()
        }

        pWCategory.setOnDismissListener {
            mDatabind.tvCategory.setTextColor(ContextCompat.getColor(this, R.color.comm_text_gray_dark))
            mDatabind.ivCategory.setBackgroundResource(R.mipmap.icon_arrow_down_solid)
            mDatabind.ivCategory.animate().rotationBy(-180F).setDuration(300).start()
        }

        pWSex.setOnDismissListener {
            mDatabind.tvSex.setTextColor(ContextCompat.getColor(this, R.color.comm_text_gray_dark))
            mDatabind.ivSex.setBackgroundResource(R.mipmap.icon_arrow_down_solid)
            mDatabind.ivSex.animate().rotationBy(-180F).setDuration(300).start()
        }

        pWYear.setOnDismissListener {
            mDatabind.tvYear.setTextColor(ContextCompat.getColor(this, R.color.comm_text_gray_dark))
            mDatabind.ivYear.setBackgroundResource(R.mipmap.icon_arrow_down_solid)
            mDatabind.ivYear.animate().rotationBy(-180F).setDuration(300).start()
        }

        pWCategory.setOnItemClickListener { _, _, position, _ ->
            mCategory = mCategoryList[position]
            val result = if (mCategory == "全部") {
                getString(R.string.category)
            } else {
                mCategory
            }
            mDatabind.tvCategory.text = result
            adapterCategory?.setCheckItem(position)
            pWCategory.dismiss()
            onRefresh(isRefresh = true)
        }

        pWStatus.setOnItemClickListener { _, _, position, _ ->
            mStatus = mStatusList[position]
            val result = if (mStatus == "全部") {
                getString(R.string.pigeon_status)
            } else {
                mStatus
            }
            mDatabind.tvStatus.text = result
            adapterStatus?.setCheckItem(position)
            pWStatus.dismiss()
            onRefresh(isRefresh = true)
        }

        pWSex.setOnItemClickListener { _, _, position, _ ->
            val sex = mSexList[position]
            mSex = when (sex) {
                "雌鸽" -> {
                    getString(R.string.hint_female)//"雌"
                }

                "雄鸽" -> {
                    getString(R.string.hint_male)//"雄"
                }

                else -> {
                    sex
                }
            }
            val result = if (sex == "全部") {
                getString(R.string.pigeon_sex)
            } else {
                sex
            }
            adapterSex?.setCheckItem(position)
            mDatabind.tvSex.text = result
            pWSex.dismiss()
            onRefresh(isRefresh = true)
        }

        pWYear.setOnItemClickListener { _, _, position, _ ->
            mYear = mYearList[position]
            val result = if (mYear == "全部") {
                getString(R.string.hint_foot_ring_number_year)
            } else {
                mYear
            }
            mDatabind.tvYear.text = result
            adapterYear?.setCheckItem(position)
            pWYear.dismiss()
            onRefresh(isRefresh = true)
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            startActivity<ActivityBloodPigeonInfo>("pigeonId" to mAdapter.data[position].id, "isAmend" to true)
        }

        mAdapter.addChildClickViewIds(R.id.ivItemImageView)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.ivItemImageView -> {
                    val imageList = arrayListOf<String>()
                    if (mAdapter.data.isNotEmpty()) {
                        mAdapter.data.forEach {
                            imageList.add(it.img)
                        }
                    }
                    openAdapterBigImage(position, mDatabind.includeList.swipeRecyclerView, imageList)
                }
            }
        }
    }

    private fun setYearListPopup(list: List<String>) {
        mYearList.clear()
        mYearList.add(0, getString(R.string.activity_mine_account_transaction_type1_all))
        mYearList.addAll(list)
        /** 初始化ListPopupWindow，适配 */
        adapterYear = MyPopBloodLineAdapter(this, mYearList)
        pWYear.setAdapter(adapterYear)
        pWYear.anchorView = mDatabind.llCategory//设置ListPopupWindow的锚点，关联mButton位置
        pWYear.width = LinearLayout.LayoutParams.MATCH_PARENT
        pWYear.height = LinearLayout.LayoutParams.WRAP_CONTENT
        pWYear.isModal = true
        pWYear.show()
    }

    private fun setSexListPopup() {
        mSexList.clear()
        mSexList.add(getString(R.string.activity_mine_account_transaction_type1_all))
        mSexList.add(getString(R.string.female_pigeon))
        mSexList.add(getString(R.string.male_pigeon))
        mSexList.add(getString(R.string.hint_unknown))
        /** 初始化ListPopupWindow，适配 */
        adapterSex = MyPopBloodLineAdapter(this, mSexList)
        pWSex.setAdapter(adapterSex)
        pWSex.anchorView = mDatabind.llCategory//设置ListPopupWindow的锚点，关联mButton位置
        pWSex.width = LinearLayout.LayoutParams.MATCH_PARENT
        pWSex.height = LinearLayout.LayoutParams.WRAP_CONTENT
        pWSex.isModal = true
    }

    private fun setStatusListPopup(list: List<BreedStatusList>) {
        mStatusList.clear()
        mStatusList.add(0, getString(R.string.activity_mine_account_transaction_type1_all))
        if (list.isNotEmpty()) {
            list.forEach {
                mStatusList.add(it.state)
            }
        }
        /** 初始化ListPopupWindow，适配 */
        adapterStatus = MyPopBloodLineAdapter(this, mStatusList)
        pWStatus.setAdapter(adapterStatus)
        pWStatus.anchorView = mDatabind.llCategory//设置ListPopupWindow的锚点，关联mButton位置
        pWStatus.width = LinearLayout.LayoutParams.MATCH_PARENT
        pWStatus.height = LinearLayout.LayoutParams.WRAP_CONTENT
        pWStatus.isModal = true
        pWStatus.show()
    }

    private fun setCategoryListPopup(list: List<BreedCategoryBean>) {
        mCategoryList.clear()
        mCategoryList.add(0, getString(R.string.activity_mine_account_transaction_type1_all))
        if (list.isNotEmpty()) {
            list.forEach {
                mCategoryList.add(it.category)
            }
        }
        /** 初始化ListPopupWindow，适配 */
        adapterCategory = MyPopBloodLineAdapter(this, mCategoryList)
        pWCategory.setAdapter(adapterCategory)
        pWCategory.anchorView = mDatabind.llStatus//设置ListPopupWindow的锚点，关联mButton位置
        pWCategory.width = LinearLayout.LayoutParams.MATCH_PARENT
        pWCategory.height = LinearLayout.LayoutParams.WRAP_CONTENT
        pWCategory.isModal = true
        pWCategory.show()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.ivBack,
            mDatabind.includeSearch.tvSearch,
            mDatabind.includeSearch.ivClose,
            mDatabind.llStatus,
            mDatabind.llCategory,
            mDatabind.llSex,
            mDatabind.llYear,
            mDatabind.tvAddBloodPigeon,
        ) {
            when (it) {
                mDatabind.tvAddBloodPigeon -> startActivity<ActivityAddBloodPigeon>("type" to 1, "isAmend" to true)
                mDatabind.llYear -> mViewModel.getYearList()
                mDatabind.llSex -> refreshArrowStatus(3)
                mDatabind.llCategory -> mViewModel.getPgBreedCategory()
                mDatabind.llStatus -> mViewModel.getPgBreedStatus()
                mDatabind.includeSearch.ivClose -> {
                    mDatabind.includeSearch.editQuery.setText("")
                    onRefresh(isRefresh = true)
                }

                mDatabind.includeSearch.tvSearch -> {
                    if (mDatabind.includeSearch.editQuery.text.toString().trim().isEmpty()) {
                        RxToast.warning(getString(R.string.input_search_content))
                        return@setOnclickNoRepeat
                    }
                    onRefresh(isRefresh = true)
                }

                mDatabind.ivBack -> finish()
            }
        }
    }

    private fun refreshArrowStatus(isPressedContent: Int) {
        when (isPressedContent) {
            1 -> {
                mDatabind.tvStatus.setTextColor(ContextCompat.getColor(this, R.color.color_red))
                mDatabind.ivStatus.setBackgroundResource(R.mipmap.icon_arrow_down_solid_red)
                mDatabind.ivStatus.animate().rotationBy(180F).setDuration(300).start()
            }

            2 -> {
                mDatabind.tvCategory.setTextColor(ContextCompat.getColor(this, R.color.color_red))
                mDatabind.ivCategory.setBackgroundResource(R.mipmap.icon_arrow_down_solid_red)
                mDatabind.ivCategory.animate().rotationBy(180F).setDuration(300).start()
            }

            3 -> {
                pWSex.show()
                mDatabind.tvSex.setTextColor(ContextCompat.getColor(this, R.color.color_red))
                mDatabind.ivSex.setBackgroundResource(R.mipmap.icon_arrow_down_solid_red)
                mDatabind.ivSex.animate().rotationBy(180F).setDuration(300).start()
            }

            4 -> {
                mDatabind.tvYear.setTextColor(ContextCompat.getColor(this, R.color.color_red))
                mDatabind.ivYear.setBackgroundResource(R.mipmap.icon_arrow_down_solid_red)
                mDatabind.ivYear.animate().rotationBy(180F).setDuration(300).start()
            }
        }
    }

    private fun onRefresh(isRefresh: Boolean) {
        val ringOrName = mDatabind.includeSearch.editQuery.text.toString().trim()
        if (isRefresh) {
            loadSir.showLoading()
        }
        mViewModel.getBreedingPigeonList(isRefresh, mStatus, mCategory, mSex, mYear, ringOrName, "", "", "")
    }
}